var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./src/routes/index');
var usersRouter = require('./src/routes/modules/users');
var ideasRouter = require('./src/routes/modules/ideas');

var app = express();

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

/**
 * 模板引擎
 * @type handlebars
 */
const exphbs = require('express-handlebars');
app.engine('handlebars', exphbs({
    defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
/**
 * 中间件
 * @type body-parser
 */
// const bodyParser = require('body-parser');
// const jsonParser = bodyParser.json();
// const urlencodedParser = bodyParser.urlencoded({extended: false});
// app.use(jsonParser)
// app.use(urlencodedParser)
// 注解
const methodOverride  = require('method-override');
app.use(methodOverride('_method'));
// 存储
const session = require('express-session');
app.use(session({
    secret: 'modh', // 密钥
    resave: true,
    saveUninitialized: true
}))

const passport = require('./config/auth.config')
app.use(passport.initialize());
app.use(passport.session());

const flash = require('connect-flash');
app.use(flash());
// 全局变量
app.use((req, res, next) => {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
})
/**
 * 静态文件
 * @type static file
 */
app.use(express.static(path.join(__dirname, 'public')));

/**
 * 链接数据库
 * @type mongoose
 */
require('./config/mongoose.config');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/ideas', ideasRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
